//
//  TableViewController.m
//  FMDB-名片
//
//  Created by Hello Cai on 16/2/18.
//  Copyright © 2016年 Hello Cai. All rights reserved.
//

#import "TableViewController.h"
#import "FMDatabase.h"
#import "DiyCell.h"
#import "DataBaseManager.h"
#import "DetailViewController.h"

@interface TableViewController ()

@property(nonatomic,copy)NSMutableArray *dataArr;

@end

@implementation TableViewController

-(NSMutableArray *)dataArr{
    if(_dataArr == nil){
        _dataArr = [NSMutableArray new];
    }
    return _dataArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //清空旧数据
    if(self.dataArr.count!=0){
        [self.dataArr removeAllObjects];
    }
    
    //数据源数组加载数据
    [self.dataArr addObjectsFromArray:[[DataBaseManager shareDatabase] searchFromDatabase]];
    
    //刷新
    [self.tableView reloadData];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    DiyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.personModel = _dataArr[indexPath.row];
    return cell;
}

/**
 *  自定义左滑出现的按钮（当实现了这个方法，编辑模式下返回的就是我们自定义的按钮，则系统的删除功能tableView:commitEditingStyle:forRowAtIndexPath:就会失效）
 */
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewRowAction *action = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"修改" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        DetailViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"DetailViewController"];
        vc.personModel = self.dataArr[indexPath.row];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    
    UITableViewRowAction *action2 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        [[DataBaseManager shareDatabase] deletePerson:self.dataArr[indexPath.row]];
        
        [self.dataArr removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }];
    return @[action2, action];
}
@end
